#!/usr/bin/env python

import sys
from sqlite3 import dbapi2 as sqlite
from hippo import OptionParser as OptionParser
import datetime
import urllib2

def main(args=None):
    if args == None:
        args = sys.argv[1:]

    parser = OptionParser(config_file='overflow.config')
    parser.add_option('-c', '--cookie', help='beta cookie - called "soba" in the page info')
    parser.add_option('-u', '--user', type=int, help='user number')
    (options, args) = parser.parse_args(args)

    connection = sqlite.connect('profile.db') #profile.db goes in the same directory that os.chdir used earlier
    connection.row_factory = sqlite.Row
    cursor = connection.cursor()
    cursor.execute('SELECT rep, date FROM profile WHERE user = :user ORDER BY date ASC;', options.__dict__)
    row = cursor.next()
    firstDate = datetime.datetime.strptime(row['date'], '%Y-%m-%d %H:%M:%S')
    data = []
    minRep = row['rep'] 
    data.append((0,minRep))

    for row in cursor:
        lastDate = datetime.datetime.strptime(row['date'], '%Y-%m-%d %H:%M:%S')
        
        offset = lastDate - firstDate
        maxOffset = offset.days * 86400 + offset.seconds
        maxRep = row['rep']
        data.append((maxOffset, maxRep))

#http://chart.apis.google.com/chart?cht=lxy&chs=200x125&chd=t:0,30,60,70,90,95,100|20,30,40,50,60,70,80|10,30,40,45,52|100,90,40,20,10|-1|5,33,50,55,7&chco=3072F3,ff0000,00aaaa&chls=2,4,1&chm=s,FF0000,0,-1,5|s,0000ff,1,-1,5|s,00aa00,2,-1,5

#          + '|1:|' + str(minRep) + '|' + str(maxRep) + '|' \

    url ='http://chart.apis.google.com/chart?cht=lxy&chs=600x500' \
          + '&chxt=x,y' \
          + '&chxl=0:|' + str(firstDate.date()) + '|' + str(lastDate.date()) \
          + '|1:|' + str(minRep) + '|' + str(maxRep) \
          + '&chd=t:' \
          + ','.join(['%.1f' %(float(d[0])*100/maxOffset) for d in data]) \
          + '|' \
          + ','.join(['%.1f' %(float(d[1])*100/maxRep) for d in data]) 
#       + '&chds:' \
#       + str(data[0][0]) + ',' + str(data[-1][0]) + ',' \
#       + str(data[0][1]) + ',' + str(data[-1][1]) 


#    print url
    file('t.png', 'wb').write(urllib2.urlopen(url).read())

    return 0


if __name__ == '__main__':
    sys.exit(main())

